﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    var nav = WinJS.Navigation;

    WinJS.UI.Pages.define("/pages/itemdetail/itemdetail.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        itemInvoked: function (args) {
            var item = args.detail;
            nav.navigate("/pages/imageZoom/imagezoom.html", {
                ItemDetail: item,
                ScreenshotsData: WinJS.Application.sessionState.JSONScreenshotsData,
                ApplicationName: WinJS.Application.sessionState.ApplicationName
            });
        },

        ready: function (element, options) {
            // TODO: Initialize the page here.

            var imageList = element.querySelector('#imagesList').winControl;
            imageList.oniteminvoked = this.itemInvoked.bind(this);

            var WService = WindowsStoreWRC.WRCServiceCom;
            WService.dadosPrograma(options.itemID).done(
            function complete(result) {

                var JSONResult = JSON.parse(result);

                /* Gratuito ou Gratuito para testar */
                JSONResult.Paid = ((JSONResult.Paid == false) ? "Gratuito" : "Gratuito para testar");

                /* Avaliação */
                JSONResult.RateInteger = parseInt(JSONResult.Rate);

                /* Nome do Programa */
                element.querySelector('.pagetitle').textContent = JSONResult.Name;

                /* Pequena Descrição */
                element.querySelector('.itemDescription').innerHTML = JSONResult.ShortDescription;

                if (JSONResult.NossaOpiniao.length == 0 || JSONResult.NossaOpiniao == 'null')
                    element.querySelector('.itemOpinionArea').style.display = 'none';
                else {
                    var textElement = element.querySelector(".itemOpinionText");
                    textElement.innerHTML = JSONResult.NossaOpiniao;
                    element.querySelector(".itemOpinionArea").style.width = WinJS.Utilities.getTotalWidth(textElement) + 'px';
                }

                /* Descrição Completa */
                element.querySelector('.itemFullText').innerHTML = JSONResult.Description;
                
                element.querySelector('.itemFullArea').style.width = WinJS.Utilities.getTotalWidth(element.querySelector('.itemFullText')) + 'px';

                /* Ícone */
                element.querySelector('.itemIcon').src = "http://www.baixaki.com.br/imagens/" + JSONResult.IconURL + ".jpg";

                /* Idioma */
                element.querySelector('.itemLanguageText').textContent = ((JSONResult.Idioma == 1) ? "Português" : "Inglês");

                /* Desenvolvedor */
                element.querySelector('.itemPublisherText').textContent = JSONResult.Developer;

                /* Total de downloads */
                element.querySelector('.itemDownloadsText').textContent = addCommas(JSONResult.DownloadCount);

                /* Total de votos */
                element.querySelector('.itemRatingLabel').textContent = addCommas(JSONResult.Votes) + " votos";

                /* Se é gratuito ou não */
                element.querySelector('.itemLicenseText').textContent = JSONResult.Paid;

                /* Tamanho em KB */
                element.querySelector('.itemSizeText').textContent = addCommas(getBytesWithUnit(JSONResult.Size * 1024));

                /* Data de Atualização do aplicativo no Baixaki */
                element.querySelector('.itemUpdateText').textContent = "Atualizado em " + JSONResult.UpdatedAt;

                /* Avaliação */
                var ratingControl = element.querySelector('.itemRating').winControl;
                ratingControl.averageRating = JSONResult.RateInteger;

                /* Pros e Contras */
                if (JSONResult.Pros.length == 0 && JSONResult.Contras.length == 0)
                    element.querySelector('.itemProsConsArea').style.display = 'none';
                else {
                    var ArrayPros = JSONResult.Pros.split("\n");
                    var ProsContent = '';
                    for (var i = 0; i < ArrayPros.length; i++) {
                        ProsContent += '<li>' + ArrayPros[i].replace('\r', '') + '</li>';
                    }
                    element.querySelector('#prosList').innerHTML = ProsContent;

                    var ArrayContras = JSONResult.Contras.split("\n");
                    var ContrasContent = '';
                    for (var i = 0; i < ArrayContras.length; i++) {
                        ContrasContent += '<li>' + ArrayContras[i].replace('\r', '') + '</li>';
                    }
                    element.querySelector('#consList').innerHTML = ContrasContent;
                }

                /* Thumbs das Screenshots */
                var imagesScreenhots = JSON.parse(JSONResult.Screenshots);

                /* Infos para a pagina de screenshots */
                if (imagesScreenhots.length > 0) {
                    WinJS.Application.sessionState.JSONScreenshotsData = JSON.parse(JSONResult.Screenshots);
                    WinJS.Application.sessionState.ApplicationName = JSONResult.Name;

                    for (var i = 0; i < imagesScreenhots.length; i++) {
                        imagesScreenhots[i].Path = "http://www.baixaki.com.br/imagens/" + imagesScreenhots[i].Path + "-t.jpg";
                    }

                    var screenshotsBind = new WinJS.Binding.List(imagesScreenhots);
                    WinJS.Namespace.define("ListScreenshots", {
                        images: screenshotsBind
                    });

                    imageList.itemDataSource = ListScreenshots.images.dataSource;
                }
                else {
                    element.querySelector(".itemImagesArea").style.display = 'none';
                }

                var btnDownload = element.querySelector('.itemDownloadButton');
                btnDownload.addEventListener('click', function () {
                    Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri('http://www.baixaki.com.br/download/' + JSONResult.UrlDetail + '.htm'));
                }, false);

                element.querySelector('[role=main]').focus();
            });

            // Images list width adjust
            var imagesListView = element.querySelector("#imagesList").winControl;
            imagesListView.addEventListener("loadingstatechanged", function () {
                var imagesHolder = element.querySelector("#imagesList");
                var imagesInner = element.querySelector("#imagesList .win-surface");
                imagesHolder.style.width = WinJS.Utilities.getTotalWidth(imagesInner) + "px";
            }, false);

            // Fake alert
            function alert(content, title) {
                var messageDialog = new Windows.UI.Popups.MessageDialog(content, title);
                messageDialog.showAsync();
            }

            function addCommas(nStr) {
                nStr += '';
                var x = nStr.split('.');
                var x1 = x[0];
                var x2 = x.length > 1 ? '.' + x[1] : '';
                var rgx = /(\d+)(\d{3})/;
                while (rgx.test(x1)) {
                    x1 = x1.replace(rgx, '$1' + '.' + '$2');
                }
                return x1 + x2;
            }

            var getBytesWithUnit = function (bytes) {
                if (isNaN(bytes)) { return; }
                var units = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
                var amountOf2s = Math.floor(Math.log(+bytes) / Math.log(2));
                if (amountOf2s < 1) {
                    amountOf2s = 0;
                }
                var i = Math.floor(amountOf2s / 10);
                bytes = +bytes / Math.pow(2, 10 * i);

                // Rounds to 3 decimals places.
                if (bytes.toString().length > bytes.toFixed(3).toString().length) {
                    bytes = bytes.toFixed(0);
                }
                return bytes + units[i];
            };
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in viewState.
        }
    });
})();
